package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;

public class CcsNewsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet=false;

		String[] regex={
							"http://www.ccs.cn/.*/news/[0-9]{4}-[0-9]{1,2}/[0-9]+_[0-9]+.shtml"
							};
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				bRet=true;
				break;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		String html=urlMeta.getHtml();
		if (html == null) {
		}
		String title="";
		String content="";
		Long date=0l;
		int commentNum=0;
		int clickNum=0;
		NewsMeta meta=new NewsMeta();
		meta.setUrl(url);
		meta.setType(0);
		Document doc=Jsoup.parse(html);
		urlMeta=null;
		/*
		 * 解析新闻标题
		 */
		title=doc.select("span#newstitle").text();
		/*
		 * 解析时间
		 */
		date=DateUtils.matchDate(doc.select("span#newsdate").text());
		/*
		 * 解析内容
		 */
		content=HtmlCleaner.getContentHtml(url ,doc.select("span#newscontent"));
		/**
		 * 初始化、截取 、设置作者信息*******************************************
		 *
		 * */
//		String str=null;
		String author=null;
		author=doc.select("span#sitetitle").text();
//		author=StringUtils.substringBetween(str,"来源：","编辑：");
		meta.setAuthor(author);
		/**
		 *                        	 **************************end *************************
		 *
		 **/
		meta.setTitle(title);
		meta.setContent(content);
		meta.setDate(date);
		meta.setClickNum(clickNum);
		meta.setCommentNum(commentNum);

		return meta;
	}


	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		String url="http://www.ccs.cn/news/news/2016-11/2440_140221.shtml";
		UrlMeta urlMeta=CrawlHTML.responseToURL(url);
		CcsNewsAnalyse a=new CcsNewsAnalyse();
		boolean detailPage=a.isDetailPage(url);
		if (detailPage) {
			NewsMeta parserHtml=a.parserHtml(urlMeta);
			System.out.println(parserHtml);
		} else {
			System.out.println("不符合正则");
		}

	}
	
	public boolean isNeedUpdate(){
		return false;
	}
}
